package com.beardedcoder.lowPower.dao.impl;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import com.beardedcoder.lowPower.dao.BatteryDao;
import com.beardedcoder.lowPower.dao.DbLowPower;
import com.beardedcoder.lowPower.model.BatteryData;

public final class BatteryDaoImpl implements BatteryDao
{
	private static final String TABLE = "batteryinfo";
	private static final String COL_ID = "id";
	private static final String COL_DATETIME = "datetime";
	private static final String COL_POWERLEVEL = "powerlevel";
	private static final String COL_VOLTAGE = "voltage";
	private static final String COL_HEALTH = "health";
	private static final String COL_STATUS = "status";
	private static final String COL_TECH = "tech";
	private static final String COL_TEMPERATURE = "temperature";
	private static final String COL_SOURCE = "source";
	private static final int FIELD_COUNT = 8;
	
	private DbLowPower dbLowPower;
	private SQLiteDatabase database;
	
	/**
	 * Create a BatteryDao implementation.
	 * @param dbLowPower
	 */
	public BatteryDaoImpl(DbLowPower dbLowPower)
	{
		this.dbLowPower = dbLowPower;
		open();
	}
	
	/**
	 * Open the database for reading and writing.
	 * @throws SQLiteException if the database cannot be opened for writing.
	 */
	public void open()
	{
		database = dbLowPower.getWritableDatabase();
	}
	
	/**
	 * Close the database if open.
	 */
	public void close()
	{
		if (database!= null)
			
		{		
			database.close();
			database = null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public void insert(BatteryData battery)
	{
		if (battery == null) throw new NullPointerException("Battery to insert cannot be null");

		long rowId = database.insertOrThrow(TABLE, null, buildContentValues(battery));
		battery.setId(rowId);
	}
	
	private ContentValues buildContentValues(BatteryData battery)
	{
		ContentValues values = new ContentValues(FIELD_COUNT);
		values.put(COL_DATETIME, battery.getOccurred().getTimeInMillis());
		values.put(COL_HEALTH, battery.getHealth());
		values.put(COL_POWERLEVEL, battery.getPowerLevel());
		values.put(COL_SOURCE, battery.getPowerSource());
		values.put(COL_STATUS, battery.getStatus());
		values.put(COL_TECH, battery.getTechnology());
		values.put(COL_TEMPERATURE, battery.getTemperature());
		values.put(COL_VOLTAGE, battery.getVoltage());
		
		return values;
	}

	@Override
	public BatteryData findById(long id)
	{
		// TODO Auto-generated method stub
		return null;
	}

}
